package cn.iocoder.yudao.module.book.controller.app.follow;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.book.controller.admin.checkIn.vo.CheckInPageReqVO;
import cn.iocoder.yudao.module.book.controller.app.lock.vo.AppCheckInEnhancedRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.checkIn.CheckInDO;
import cn.iocoder.yudao.module.book.service.checkIn.CheckInService;
import cn.iocoder.yudao.module.book.service.follow.UserFollowService;
import cn.iocoder.yudao.module.book.service.books.BooksService;
import cn.iocoder.yudao.module.book.service.records.RecordsService;
import cn.iocoder.yudao.module.book.dal.dataobject.records.RecordsDO;
import cn.iocoder.yudao.module.book.service.users.userDTOService;
import cn.iocoder.yudao.module.book.constants.UserConstants;
import cn.iocoder.yudao.module.book.controller.app.bookcase.vo.AppBooksRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.users.userDTODO;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 用户关注 APP Controller
 *
 * @author 系统管理员
 */
@Tag(name = "用户 APP - 用户关注")
@RestController
@RequestMapping("/api/user/follow")
@Slf4j
public class AppUserFollowController {

    @Resource
    private UserFollowService userFollowService;
    
    @Resource
    private CheckInService checkInService;
    
    @Resource
    private userDTOService userService;
    
    @Resource
    private BooksService booksService;
    
    @Resource
    private RecordsService recordsService;

    @PostMapping("/toggle")
    @Operation(summary = "关注/取消关注用户")
    public CommonResult<Boolean> toggleFollow(@RequestBody ToggleFollowReqVO reqVO) {
        Long currentUserId = userService.getCurrentUserId();
        
        if (currentUserId.equals(reqVO.getTargetUserId())) {
            return CommonResult.error(500, "不能关注自己");
        }
        
        Boolean isFollowing = userFollowService.isFollowing(currentUserId, reqVO.getTargetUserId());
        
        if (isFollowing) {
            // 取消关注
            Boolean result = userFollowService.unfollowUser(currentUserId, reqVO.getTargetUserId());
            return success(!result); // 取消关注成功返回false
        } else {
            // 关注
            Boolean result = userFollowService.followUser(currentUserId, reqVO.getTargetUserId());
            return success(result); // 关注成功返回true
        }
    }

    @GetMapping("/check/{targetUserId}")
    @Operation(summary = "检查是否关注某用户")
    public CommonResult<Boolean> checkFollow(@PathVariable("targetUserId") Long targetUserId) {
        Long currentUserId = userService.getCurrentUserId();
        Boolean isFollowing = userFollowService.isFollowing(currentUserId, targetUserId);
        return success(isFollowing);
    }

    @GetMapping("/following")
    @Operation(summary = "获取我的关注列表")
    public CommonResult<List<Long>> getFollowingList() {
        Long currentUserId = userService.getCurrentUserId();
        List<Long> followingList = userFollowService.getFollowingList(currentUserId);
        return success(followingList);
    }

    @GetMapping("/followers")
    @Operation(summary = "获取我的粉丝列表")
    public CommonResult<List<Long>> getFollowersList() {
        Long currentUserId = userService.getCurrentUserId();
        List<Long> followersList = userFollowService.getFollowersList(currentUserId);
        return success(followersList);
    }

    @GetMapping("/stats")
    @Operation(summary = "获取关注统计信息")
    public CommonResult<FollowStatsRespVO> getFollowStats() {
        Long currentUserId = userService.getCurrentUserId();
        Long followingCount = userFollowService.getFollowingCount(currentUserId);
        Long followersCount = userFollowService.getFollowersCount(currentUserId);
        
        FollowStatsRespVO stats = new FollowStatsRespVO();
        stats.setFollowingCount(followingCount);
        stats.setFollowersCount(followersCount);
        return success(stats);
    }

    @GetMapping("/checkins/latest")
    @Operation(summary = "获取最新打卡记录")
    public CommonResult<List<AppCheckInEnhancedRespVO>> getLatestCheckins(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        CheckInPageReqVO pageReqVO = new CheckInPageReqVO();
        pageReqVO.setPageNo(page + 1); // 前端传0开始，后端1开始
        pageReqVO.setPageSize(pageSize);
        
        PageResult<CheckInDO> pageResult = checkInService.getLatestCheckInPage(pageReqVO);
        List<AppCheckInEnhancedRespVO> enhancedList = convertToEnhancedList(pageResult.getList());
        
        return success(enhancedList);
    }

    @GetMapping("/checkins/following")
    @Operation(summary = "获取关注用户的打卡记录")
    public CommonResult<List<AppCheckInEnhancedRespVO>> getFollowingCheckins(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        Long currentUserId = userService.getCurrentUserId();
        List<Long> followingList = userFollowService.getFollowingList(currentUserId);
        
        if (followingList.isEmpty()) {
            return success(new ArrayList<>());
        }
        
        CheckInPageReqVO pageReqVO = new CheckInPageReqVO();
        pageReqVO.setPageNo(page + 1);
        pageReqVO.setPageSize(pageSize);
        
        PageResult<CheckInDO> pageResult = checkInService.getFollowingCheckInPage(followingList, pageReqVO);
        List<AppCheckInEnhancedRespVO> enhancedList = convertToEnhancedList(pageResult.getList());
        
        // 标记关注状态
        for (AppCheckInEnhancedRespVO item : enhancedList) {
            if (item.getUserInfo() != null) {
                item.getUserInfo().setIsFollowing(true);
            }
        }
        
        return success(enhancedList);
    }

    @GetMapping("/checkins/my")
    @Operation(summary = "获取我的打卡记录")
    public CommonResult<List<AppCheckInEnhancedRespVO>> getMyCheckins(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        Long currentUserId = userService.getCurrentUserId();
        
        CheckInPageReqVO pageReqVO = new CheckInPageReqVO();
        pageReqVO.setPageNo(page + 1);
        pageReqVO.setPageSize(pageSize);
        
        PageResult<CheckInDO> pageResult = checkInService.getUserCheckInPage(currentUserId, pageReqVO);
        List<AppCheckInEnhancedRespVO> enhancedList = convertToEnhancedList(pageResult.getList());
        
        return success(enhancedList);
    }

    /**
     * 转换为增强响应列表
     */
    private List<AppCheckInEnhancedRespVO> convertToEnhancedList(List<CheckInDO> checkInList) {
        List<AppCheckInEnhancedRespVO> enhancedList = new ArrayList<>();
        Long currentUserId = userService.getCurrentUserId();
        
        for (CheckInDO checkIn : checkInList) {
            AppCheckInEnhancedRespVO enhancedVO = new AppCheckInEnhancedRespVO();
            enhancedVO.setClockId(checkIn.getClockId());
            enhancedVO.setContent(checkIn.getContent());
            enhancedVO.setDayCount(checkIn.getDayCount());
            enhancedVO.setCreateTime(checkIn.getCreateTime());
            
            // 用户信息
            userDTODO user = userService.getuserDTO(checkIn.getUserId());
            if (user != null) {
                AppCheckInEnhancedRespVO.UserInfo userInfo = new AppCheckInEnhancedRespVO.UserInfo();
                userInfo.setUserId(user.getUserId());
                userInfo.setNickName(user.getNickname());
                userInfo.setAvatar(user.getAvatarUrl() != null ? user.getAvatarUrl() : UserConstants.DEFAULT_AVATAR_URL);
                userInfo.setIsVip(user.getIsMember());
                
                // 检查关注状态（除了自己）
                if (!checkIn.getUserId().equals(currentUserId)) {
                    Boolean isFollowing = userFollowService.isFollowing(currentUserId, checkIn.getUserId());
                    userInfo.setIsFollowing(isFollowing);
                }
                
                enhancedVO.setUserInfo(userInfo);
            }
            
            // 书籍信息（优先使用打卡中记录的 bookList；为空时回退到当日阅读记录）
            List<AppCheckInEnhancedRespVO.BookInfo> bookInfoList = new ArrayList<>();
            if (checkIn.getBookList() != null && !checkIn.getBookList().isEmpty()) {
                List<Integer> bookIds = JSON.parseArray(checkIn.getBookList(), Integer.class);
                for (Integer bookId : bookIds) {
                    AppBooksRespVO book = booksService.getByBookId(bookId, null);
                    if (book != null) {
                        AppCheckInEnhancedRespVO.BookInfo bookInfo = new AppCheckInEnhancedRespVO.BookInfo();
                        bookInfo.setBookId(book.getBookId());
                        bookInfo.setTitle(book.getTitle());
                        bookInfo.setImage(book.getImage());
                        bookInfo.setCollectionId(book.getCollectionId());
                        bookInfo.setCreator(book.getCreator());
                        bookInfoList.add(bookInfo);
                    }
                }
            }
            
            // 回退逻辑：旧数据可能未写入 bookList，则尝试用当天阅读记录补齐
            if (bookInfoList.isEmpty() && checkIn.getCreateTime() != null) {
                String day = checkIn.getCreateTime().toLocalDate().toString();
                List<RecordsDO> dayRecords = recordsService.selectDayRecord(checkIn.getUserId(), day);
                for (RecordsDO record : dayRecords) {
                    AppBooksRespVO book = booksService.getByBookId(record.getBookId(), null);
                    if (book != null) {
                        AppCheckInEnhancedRespVO.BookInfo bookInfo = new AppCheckInEnhancedRespVO.BookInfo();
                        bookInfo.setBookId(book.getBookId());
                        bookInfo.setTitle(book.getTitle());
                        bookInfo.setImage(book.getImage());
                        bookInfo.setCollectionId(book.getCollectionId());
                        bookInfo.setCreator(book.getCreator());
                        bookInfoList.add(bookInfo);
                    }
                }
            }
            
            if (!bookInfoList.isEmpty()) {
                enhancedVO.setBookList(bookInfoList);
            }
            
            enhancedList.add(enhancedVO);
        }
        
        return enhancedList;
    }

    // 内部类
    @lombok.Data
    public static class ToggleFollowReqVO {
        @Parameter(description = "目标用户ID", required = true)
        private Long targetUserId;
    }

    @lombok.Data
    public static class FollowStatsRespVO {
        @Parameter(description = "关注数")
        private Long followingCount;
        
        @Parameter(description = "粉丝数")
        private Long followersCount;
    }

}
